import { NextResponse } from 'next/server';
import { query } from '@/lib/sqlite_db';

export async function GET() {
  try {
    // 获取今日0点
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const todayStr = today.toISOString().split('T')[0];
    
    // 获取本周一0点
    const weekStart = new Date();
    weekStart.setDate(weekStart.getDate() - (weekStart.getDay() || 7) + 1);
    weekStart.setHours(0, 0, 0, 0);
    const weekStartStr = weekStart.toISOString().split('T')[0];
    
    // 获取本月1日0点
    const monthStart = new Date(today.getFullYear(), today.getMonth(), 1);
    const monthStartStr = monthStart.toISOString().split('T')[0];
    
    // 获取本年1月1日0点
    const yearStart = new Date(today.getFullYear(), 0, 1);
    const yearStartStr = yearStart.toISOString().split('T')[0];

    // 查询各时间段的token消耗
    const [todayTokens, weekTokens, monthTokens, yearTokens] = await Promise.all([
      query('SELECT COALESCE(SUM(total_tokens), 0) as total FROM logs WHERE DATE(created_at) = ?', [todayStr]),
      query('SELECT COALESCE(SUM(total_tokens), 0) as total FROM logs WHERE DATE(created_at) >= ?', [weekStartStr]),
      query('SELECT COALESCE(SUM(total_tokens), 0) as total FROM logs WHERE DATE(created_at) >= ?', [monthStartStr]),
      query('SELECT COALESCE(SUM(total_tokens), 0) as total FROM logs WHERE DATE(created_at) >= ?', [yearStartStr])
    ]);

    const stats = {
      today: Number(todayTokens[0].total || 0),
      week: Number(weekTokens[0].total || 0),
      month: Number(monthTokens[0].total || 0),
      year: Number(yearTokens[0].total || 0),
    };

    return NextResponse.json({ data: stats });
  } catch (error) {
    console.error('获取Token统计失败:', error);
    return NextResponse.json({ data: { today: 0, week: 0, month: 0, year: 0 }, error: '获取统计失败' }, { status: 500 });
  }
}